package org.example.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.example.demo.entity.User;
import org.example.demo.service.MailService;
import org.example.demo.service.UserService;
import org.example.demo.util.AjaxResult;
import org.example.demo.util.Constants;
import org.example.demo.util.RedisCache;
import org.example.demo.util.ReturnMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class MailServiceImpl implements MailService {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String mailUserName;

    private Integer overtime = 2; // 过期时间默认为2分钟


    @Autowired
    private UserService userService;

    /**
     * 获取重置密码的验证码
     *
     * @param userEmail    用户邮箱
     * @return
     */
    @Override
    public AjaxResult getCode(String userEmail) {

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        List<User> selectUser = userService.list(queryWrapper.lambda()
                .eq(User::getEmail,userEmail));
        // 如果这个用户不存在
        if(selectUser.isEmpty()) {
            return AjaxResult.error(HttpStatus.NOT_FOUND.value(),"用户不存在");
        } else {
            // 生成邮箱验证码
            String verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);
            // 存入redis中
            redisCache.setCacheObject(Constants.MAIL_CODE_KEY + ":" + userEmail, verifyCode, overtime, TimeUnit.MINUTES);
            // 编写邮件内容
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("<html><head><title>党员发展可视化系统</title></head><body>");
            stringBuilder.append("您好<br/>");
            stringBuilder.append("您的验证码是：").append(verifyCode).append("<br/>");
            stringBuilder.append("您可以复制此验证码并返回至设备管理系统找回密码页面，以验证您的邮箱。<br/>");
            stringBuilder.append("此验证码只能使用一次，在");
            stringBuilder.append(overtime.toString());
            stringBuilder.append("分钟内有效。验证成功则自动失效。<br/>");
            stringBuilder.append("如果您没有进行上述操作，请忽略此邮件。");
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            // 发件配置并发送邮件
            try {
                MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
                mimeMessageHelper.setFrom(mailUserName);
                mimeMessageHelper.setTo(userEmail);
                mimeMessage.setSubject("邮箱验证-重置密码");
                mimeMessageHelper.setText(stringBuilder.toString(), true);
                mailSender.send(mimeMessage);
            } catch (MessagingException e) {
                e.printStackTrace();
            }
            return AjaxResult.success();
        }
    }

    @Override
    public AjaxResult checkCode(String userEmail,String code) {
        // 从redis中取出验证码
        String cacheCode = redisCache.getCacheObject(Constants.MAIL_CODE_KEY + ":" + userEmail);
        // 如果是null说明已经过期了
        if (cacheCode == null) {
            return AjaxResult.error(HttpStatus.UNPROCESSABLE_ENTITY.value(),"验证码已过期");
        } else {
            if (!cacheCode.equals(code)){
                return AjaxResult.error(HttpStatus.BAD_REQUEST.value(),"用户不存在");
            }
        }
        return AjaxResult.success();
    }
}